package com.snail.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.common.DeleteRequest;
import com.snail.mapper.BizCourseCategoryMapper;
import com.snail.mapper.BizCoursesBaseMapper;
import com.snail.model.dto.CourseCategoryIndexDto;
import com.snail.model.dto.CourseCategoryTreeDto;
import com.snail.model.dto.CourseIndexDto;
import com.snail.model.pojo.BizCourseCategory;
import com.snail.model.pojo.BizCoursesBase;
import com.snail.response.BaseResponse;
import com.snail.response.ResultUtils;
import com.snail.service.BizCourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Monica
 * @description 针对表【biz_course_category(课程分类表)】的数据库操作Service实现
 * @createDate 2025-07-17 13:16:38
 */
@Service
public class BizCourseCategoryServiceImpl extends ServiceImpl<BizCourseCategoryMapper, BizCourseCategory> implements BizCourseCategoryService {

    @Autowired
    private BizCourseCategoryMapper bizCourseCategoryMapper;

    @Autowired
    private BizCoursesBaseMapper bizCourseBaseMapper;

    @Override
    public BaseResponse<List<CourseCategoryTreeDto>> getCourseCategoryTree() {
        // 获取所有的课程分类
        List<BizCourseCategory> allCategory = bizCourseCategoryMapper.selectList(null);

        // 2. 构建树形结构
        List<CourseCategoryTreeDto> tree = buildCategoryTree(allCategory);

        return ResultUtils.success(tree);
    }

    @Override
    public BaseResponse addCourseCategory(BizCourseCategory bizCourseCategory) {
        if (bizCourseCategory == null) {
            return ResultUtils.error("参数错误");
        }
        boolean success = bizCourseCategoryMapper.insert(bizCourseCategory) > 0;
        return ResultUtils.success(success);
    }

    @Override
    public BaseResponse updateCourseCategory(BizCourseCategory bizCourseCategory) {
        if (bizCourseCategory == null) {
            return ResultUtils.error("参数错误");
        }
        boolean success = bizCourseCategoryMapper.updateById(bizCourseCategory) > 0;
        return ResultUtils.success(success);
    }

    @Override
    public BaseResponse deleteCourseCategory(DeleteRequest deleteRequest) {
        if (deleteRequest == null) {
            return ResultUtils.error("参数错误");
        }
        boolean success = bizCourseCategoryMapper.deleteById(deleteRequest.getId()) > 0;
        return ResultUtils.success(success);
    }

    @Override
    public BaseResponse<List<CourseCategoryIndexDto>> getCourseCategoryIndex() {
        List<BizCourseCategory> allCategories = bizCourseCategoryMapper.selectList(null);
        List<BizCoursesBase> allCourses = bizCourseBaseMapper.selectList(null);
        // 构建分类树
        List<CourseCategoryTreeDto> categoryTree = buildCategoryTree(allCategories);
        // 数据转换
        List<CourseCategoryIndexDto> categoryIndexes = new ArrayList<>();
        dataConversion(categoryTree,categoryIndexes);

//        }

        //  将课程挂载到对应的分类下
        List<CourseCategoryIndexDto> res = mountCoursesToCategories(categoryIndexes, allCourses);


        return ResultUtils.success(res);
    }

    private void dataConversion(List<CourseCategoryTreeDto> categoryTree, List<CourseCategoryIndexDto> categoryIndexes) {
        for (CourseCategoryTreeDto item : categoryTree) {
            CourseCategoryIndexDto categoryIndexDto = new CourseCategoryIndexDto();
            categoryIndexDto.setId(item.getId());
            categoryIndexDto.setName(item.getName());
            categoryIndexDto.setParentId(item.getParentId());
            categoryIndexDto.setCourses(new ArrayList<>());

            if (item.getChildren() != null && !item.getChildren().isEmpty()) {
                List<CourseCategoryIndexDto> childDtos = new ArrayList<>();
                dataConversion(item.getChildren(), childDtos);
                categoryIndexDto.setChildren(childDtos);
            }

            categoryIndexes.add(categoryIndexDto);
        }
    }

    /**
     *  将课程挂载到对应的分类下
     * @param categoryTree 分类树
     * @param allCourses 所有课程
     * @return
     */
    private List<CourseCategoryIndexDto> mountCoursesToCategories(List<CourseCategoryIndexDto> categoryTree,
                                                                  List<BizCoursesBase> allCourses) {
        Map<Integer, CourseCategoryIndexDto> categoryMap = new HashMap<>();
        flattenCategoryTree(categoryTree, categoryMap);

        for (BizCoursesBase course : allCourses) {
            CourseCategoryIndexDto categoryDto = categoryMap.get(course.getCategoryId());
            if (categoryDto != null) {
                CourseIndexDto courseDto = new CourseIndexDto();
                courseDto.setId(course.getId());
                courseDto.setTitle(course.getTitle());
                courseDto.setCreateTime(course.getCreateTime());

                // 确保courses列表已初始化
                if (categoryDto.getCourses() == null) {
                    categoryDto.setCourses(new ArrayList<>());
                }
                categoryDto.getCourses().add(courseDto);
            }
        }

        // 按创建时间倒序排序
        for (CourseCategoryIndexDto categoryDto : categoryMap.values()) {
            if (categoryDto.getCourses() != null) {
                categoryDto.getCourses().sort(Comparator.comparing(CourseIndexDto::getCreateTime).reversed());
            }
        }

        return categoryTree;
    }

    /**
     * 平铺树形结构，建立完整映射
     */
    private void flattenCategoryTree(List<CourseCategoryIndexDto> tree, Map<Integer, CourseCategoryIndexDto> map) {
        for (CourseCategoryIndexDto dto : tree) {
            map.put(dto.getId(), dto);
            if (dto.getChildren() != null && !dto.getChildren().isEmpty()) {
                flattenCategoryTree(dto.getChildren(), map);
            }
        }
    }
    /**
     * 构建课程分类树形结构
     *
     * @param allCategories 所有分类列表
     * @return 树形结构列表
     */
    private List<CourseCategoryTreeDto> buildCategoryTree(List<BizCourseCategory> allCategories) {
        // 1. 创建DTO映射Map和结果列表
        Map<Integer, CourseCategoryTreeDto> dtoMap = new HashMap<>();
        List<CourseCategoryTreeDto> result = new ArrayList<>();

        // 2. 先处理所有分类，创建DTO对象并放入Map
        for (BizCourseCategory category : allCategories) {
            CourseCategoryTreeDto dto = convertToDto(category);
            dtoMap.put(dto.getId(), dto);
        }

        // 3. 构建树形结构
        for (CourseCategoryTreeDto dto : dtoMap.values()) {
            Integer parentId = dto.getParentId();
            if (parentId == null || parentId == 0) {
                // 顶级分类，直接加入结果列表
                result.add(dto);
            } else {
                // 子分类，找到父分类并添加到父分类的children中
                CourseCategoryTreeDto parentDto = dtoMap.get(parentId);
                if (parentDto != null) {
                    if (parentDto.getChildren() == null) {
                        parentDto.setChildren(new ArrayList<>());
                    }
                    parentDto.getChildren().add(dto);
                }
            }
        }

        // 4. 对每层的分类按ID排序（可选）
        sortTree(result);

        return result;
    }

    /**
     * 将实体转换为DTO
     */
    private CourseCategoryTreeDto convertToDto(BizCourseCategory category) {
        CourseCategoryTreeDto dto = new CourseCategoryTreeDto();
        dto.setId(category.getId());
        dto.setName(category.getName());
        dto.setParentId(category.getParentId());
        dto.setLevel(category.getLevel());
        return dto;
    }

    /**
     * 对树形结构进行排序（按ID升序）
     */
    private void sortTree(List<CourseCategoryTreeDto> tree) {
        if (tree == null) {
            return;
        }

        // 排序当前层级
        tree.sort(Comparator.comparing(CourseCategoryTreeDto::getId));

        // 递归排序子层级
        for (CourseCategoryTreeDto dto : tree) {
            if (dto.getChildren() != null && !dto.getChildren().isEmpty()) {
                sortTree(dto.getChildren());
            }
        }
    }
}




